package com.lsy.weizhi2.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.ImageJson;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.customview.GlideCircleTransform;
import com.lsy.weizhi2.mybase.BaseApp;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mybase.MyTitleView;
import com.lsy.weizhi2.myutils.SendPhotoCall;
import com.lsy.weizhi2.picture.PicturePopup;
import com.lsy.weizhi2.picture.PictureUtils;
import com.lsy.weizhi2.utils.BitmapUtils;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Setting_Head extends MyBaseActivity {
    private Context context;
    private MyTitleView head_title;
    private ImageView head_head;
    private Button head_btn;
    private int avatar,xx;
    private Gson gson;
    private Handler handler=new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting__head);
        context=Setting_Head.this;
        gson=new Gson();
        findView();
    }

    private void findView() {
        head_title= (MyTitleView) findViewById(R.id.head_title);
        head_head= (ImageView) findViewById(R.id.head_head);
        head_btn= (Button) findViewById(R.id.head_btn);
        head_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new PicturePopup().init(context, new SendPhotoCall() {
                    @Override
                    public void Request(String message) {
                        if (message != null) {
                            try {
                                Log.i("Setting_Head", "message=s=image=" + message);
                                ImageJson imageJson = gson.fromJson(message, ImageJson.class);
                                avatar = imageJson.getData().getId();
                                Glide.with(context)
                                        .load(new GlideUrl(Constants.DOWN_USER_PICTURE+avatar,new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                                        .transform(new GlideCircleTransform(context))
                                        .error(R.mipmap.default_head)
                                        .into(head_head);
                            } catch (Exception e) {
                                Log.i("Setting_Head", "message=f=image=" + message);
                            }
                        }
                    }
                });
            }
        });
        head_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(avatar!=0){
                    Updata();
                }
            }
        });
    }

    private void Updata(){
        Map<String,String> map=new HashMap<>();
        map.put("avatar",avatar+"");
        MyOkHttpUtils.getInstance(context).doPut(Constants.RESET_HEAD,map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject json=new JSONObject(message);
                                boolean result=json.getBoolean("result");
                                if(result){
                                    MyMethod.showToast(context,"修改成功");
                                }else{
                                    MyMethod.toActivity(context,LoginActivty.class);
                                }
                                finish();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        xx = 0;
        ViewTreeObserver vto = head_title.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(head_title.getLayoutParams());
                            params.height = MyHeight.ACTIONBAR + MyHeight.MyTitleHeight;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                head_title.setLayoutParams(params);
                            }
                        }
                    });
                }
            }
        });
        Glide.with(context).load(new GlideUrl(Constants.DOWN_USER_PICTURE+MyInfo.Avatar,new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                .transform(new GlideCircleTransform(context))
                .error(R.mipmap.default_head)
                .into(head_head);
    }

    //请求权限的返回结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PictureUtils.CAMERA) {
            for (int index = 0; index < permissions.length; index++) {
                switch (permissions[index]) {
                    case Manifest.permission.CAMERA:
                        if (grantResults[index] == PackageManager.PERMISSION_GRANTED) {
                            /**用户已经受权*/
                            startActivityForResult(
                                    new Intent(MediaStore.ACTION_IMAGE_CAPTURE), PictureUtils.CAMERA);
                        } else if (grantResults[index] == PackageManager.PERMISSION_DENIED) {
                            /**用户拒绝了权限*/
                            MyMethod.ShowDialog(context,"应用没有拍照权限，请授权！");
                        } else {
                            MyMethod.ShowDialog(context,"应用没有拍照权限，请授权！");
                        }
                        break;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureUtils.CAMERA) {
            Bitmap bitmap = data.getParcelableExtra("data");
            int count = bitmap.getByteCount();
            String path = Environment.getExternalStorageDirectory() + File.separator + "paizhao/";
            Log.i("Setting_Head", "path====" + path);
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            File file1=new File(file,"image2.png");
            if(count>=1048576){
                bitmap= BitmapUtils.getImage(bitmap);
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file1);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            UpImage(file1);
        }
    }

    private void UpImage(File file) {
        MyOkHttpUtils.getInstance(context).upLoadImage(Constants.UP_USER_PICTURE, file).excute(new MyOkHttpUtils.OKCallBack() {

            @Override
            public void onFailure(String message) {
                Log.i("Setting_Head", "message=image=Fail=" + message);
            }

            @Override
            public void onResponse(String message) {
                Log.i("Setting_Head", "message=image=Success=" + message);
                ImageJson imageJson = gson.fromJson(message, ImageJson.class);
                avatar = imageJson.getData().getId();
                Glide.with(context).load(new GlideUrl(Constants.DOWN_USER_PICTURE+avatar,new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                        .transform(new GlideCircleTransform(context))
                        .error(R.mipmap.default_head)
                        .into(head_head);
            }
        });
    }
}
